package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	commomController "ginweb/app/common/controller"
	"github.com/tidwall/gjson"
	"fmt"
	"ginweb/system"
	"time"
	"github.com/jinzhu/gorm"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/bcrypt"
)

func Reg(c *gin.Context)  {
	idkey, captcha := commomController.CaptchaCreate()
	c.HTML(http.StatusOK, "console/reg/index.html", gin.H{"idkey":idkey, "captcha":captcha})
}

func Captcha(c *gin.Context)  {
	idkey, captcha := commomController.CaptchaCreate()
	c.JSON(http.StatusOK, gin.H{"idkey":idkey, "captcha":captcha})
}

func Register(c *gin.Context)  {
	bytes, err := c.GetRawData()
	if err != nil {
		ResponseError(c, err)
		return
	}
	data := string(bytes)
	var username string
	var password string
	var key string
	var code string
	value := gjson.Get(data, "Username")
	if value.Index != 0 {
		username = value.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Username can not be empty!"))
		return
	}
	valuePwd := gjson.Get(data, "Password")
	if valuePwd.Index != 0 {
		password = valuePwd.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Password can not be empty!"))
		return
	}
	valueKey := gjson.Get(data, "Key")
	if valueKey.Index != 0 {
		key = valueKey.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Key can not be empty!"))
		return
	}
	valueCode := gjson.Get(data, "Code")
	if valueCode.Index != 0 {
		code = valueCode.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Code can not be empty!"))
		return
	}
	resVerify := commomController.VerfiyCaptcha(key, code)
	if resVerify == false {
		c.JSON(200,gin.H{"code":41004})
		return
	}
	encodePwd,err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ResponseError(c, fmt.Errorf("密码加密失败"))
		return
	}
	commomController.ConfigLocalFilesystemLogger(system.GetConfiguration().LogPath, "database.log", 7*24*time.Hour, 24*time.Hour)
	db, err := gorm.Open("mysql", system.GetConfiguration().DSN)
	if err != nil {
		log.Error("mysql连接失败：", err)
		c.JSON(200,gin.H{"code":41003})
		return
	}
	defer db.Close()
	db.AutoMigrate(&User{})
	var user User
	userInfo := db.Where("username = ?", username).First(&user)
	if userInfo.Error == nil {
		c.JSON(200,gin.H{"code":41005})
		return
	}
	////创建
	insert := User{Username:username, Password:string(encodePwd)}
	db.Create(&insert)
	c.JSON(200,gin.H{"code":200})
}